package com.example.myapplication1;

import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class CategoryListActivity extends AppCompatActivity {
    private RecyclerView rvCategoryCourses;
    private CourseAdapter courseAdapter;
    private List<Course> courseList = new ArrayList<>();
    private int categoryId;
    private Call<List<Course>> courseCall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_category_list);

        // 获取从首页传递的类别 ID
        categoryId = getIntent().getIntExtra("categoryId", 0);

        // 初始化RecyclerView
        rvCategoryCourses = findViewById(R.id.rv_category_courses);
        rvCategoryCourses.setLayoutManager(new LinearLayoutManager(this));

        courseAdapter = new CourseAdapter(this, courseList);
        rvCategoryCourses.setAdapter(courseAdapter);

        // 设置点击事件
        courseAdapter.setOnCourseClickListener(courseId -> {
            Intent intent = new Intent(CategoryListActivity.this, CourseDetailActivity.class);
            intent.putExtra("courseId", courseId);
            startActivity(intent);
        });

        // 加载类别对应的课程数据
        initCourseData();
    }

    private void initCourseData() {
        // 发起网络请求获取对应类别的课程
        courseCall = RetrofitClient.getApiService().getCoursesByCategory(categoryId);
        courseCall.enqueue(new Callback<List<Course>>() {
            @Override
            public void onResponse(Call<List<Course>> call, Response<List<Course>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    courseList.clear();
                    courseList.addAll(response.body());
                    courseAdapter.notifyDataSetChanged();
                } else {
                    Toast.makeText(CategoryListActivity.this, "获取课程失败", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<List<Course>> call, Throwable t) {
                if (!call.isCanceled()) {
                    Toast.makeText(CategoryListActivity.this, "网络错误，请重试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 取消网络请求，避免内存泄漏
        if (courseCall != null && !courseCall.isCanceled()) {
            courseCall.cancel();
        }
    }
}